
package com.rt.schedulenew.core.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.rt.schedulenew.utils.global.BusinessException;
import com.rt.schedulenew.utils.util.JsonUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;

import java.util.concurrent.TimeUnit;

/**
 * 重复提交验证
 */
@Aspect
@Configuration
public class LockMethodInterceptor {
    private static Cache<String, Object> CACHE;

    @Around("execution(public * *(..))  && @annotation(com.rt.schedulenew.utils.global.LocalLock)")
    public Object interceptor(ProceedingJoinPoint joinPoint) throws Throwable {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        String methodName = signature.getName();
        String args = JsonUtil.toJson(joinPoint.getArgs()[0]);
        String key = this.getKey(methodName, args);
        if (!StringUtils.isEmpty(key)) {
            if (LockMethodInterceptor.CACHE.getIfPresent(key) != null) {
                throw new BusinessException("请勿重复提交！");
            }
            LockMethodInterceptor.CACHE.put(key, key);
        }
        return joinPoint.proceed();
    }

    private String getKey(String methodName, String args) {
        StringBuilder sb = new StringBuilder();
        sb.append(methodName);
        sb.append(args);
        return sb.toString();
    }

    static {
        // 同一个接口2s内不能重复数据提交
        CACHE = CacheBuilder.newBuilder().maximumSize(1000L).expireAfterWrite(2L, TimeUnit.SECONDS).build();
    }
}
